package org.crazyit.app.action;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements Action,
		ServletResponseAware {
	private String username;
	private String password;
	private HttpServletResponse response;

	public String execute() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		Integer counter = (Integer) ctx.getApplication().get("counter");
		if (counter == null) {
			counter = 1;
		} else {
			counter = counter + 1;
		}
		ctx.getApplication().put("counter", counter);
		if (getUsername().equals("bm") && getPassword().equals("123")) {
			ActionContext.getContext().getSession().put("user", getUsername());
			// 通过response添加Cookie
			Cookie cookie = new Cookie("user", "cookie_" + getUsername());
			cookie.setMaxAge(60 * 60);
			response.addCookie(cookie);
			Cookie cookie2 = new Cookie("user2", getUsername());
			cookie2.setMaxAge(60 * 60);
			ServletActionContext.getResponse().addCookie(cookie2);
			ctx.put("tip", "服务器提示：您已经成功登录");
			return SUCCESS;
		} else {
			return ERROR;
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
}
